import {Component} from 'react'
import PubSub from "pubsub-js"

export default class Parent extends Component{

    render(){
        return (
            <>
            <h2>父组件</h2>
            <Child1 />
            <Child2 />
            </>
        )
    }
}


class Child1 extends Component{
    toChild2Msg = () => {
        // 发布
        PubSub.publish("receive","hello child1")
    }

    render(){
        return (
            <>
            <h2>子组件1</h2>
            <button onClick={this.toChild2Msg}>修改传值</button>
            </>
        )
    }
}

class Child2 extends Component{
    state = {
        receiveMsg:"空"
    }
    componentDidMount(){
        // 订阅
        PubSub.subscribe("receive",(msg,data) => {
            console.log(data);
            this.setState({
                receiveMsg:data
            })
        })
    }

    componentWillUnmount(){
        // 提升性能，卸载监听
        PubSub.unsubscribe("receive")
    }
    render(){
        const {receiveMsg} = this.state
        return (
            <>
            <h2>子组件2</h2>
            <div>接收到组件1的消息{receiveMsg}</div>
            </>
        )
    }
}